﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Channels.Tcp;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Sendmail.Server;

namespace Sendmail.Gui
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private SmtpServer smtpServer ;

        public MainWindow()
        {
            InitializeComponent();
            Messages = new ObservableCollection<string>();
            IChannel channel = new TcpClientChannel();
            ChannelServices.RegisterChannel(channel, false);
            Run();



        }

        public void Run()
        {
          
                try
                {
                    
                
                smtpServer = (SmtpServer)Activator.GetObject(typeof(SmtpServer), "tcp://localhost:9934/SendMailSvc");

                Dispatcher.Invoke(DispatcherPriority.Normal, new Action(LoadAccounts));
                }
            catch(Exception)
            {
                
            }
            
        }

        public void Start()
        {
            ServiceController service = new ServiceController("SendMailSvc");
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(2000);

                service.Start();
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);

                var thread1 = new Thread(this.Run);
                thread1.Start();

            }
            catch
            {
                // ...
            }
        }

        public void Stop()
        {
            ServiceController service = new ServiceController("SendMailSvc");
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(2000);

                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                //accountsBox.Items.Clear();
                //accountsBox.ItemsSource = null;
                Accounts.Clear();
                smtpServer = null;
            }
            catch
            {
                // ...
            }
        }

        public ObservableCollection<string> Accounts { get; set; }

        public void LoadAccounts()
        {
            if (smtpServer != null)
            {
                Accounts = smtpServer._accounts;
                accountsBox.ItemsSource = Accounts;
            }
            
        }


        public ObservableCollection<string> Messages { get; set; } 

        private void accountsBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {

            
            var messages = smtpServer.GetPathsToAllMailsForAccount(accountsBox.SelectedItem.ToString());
            Messages.Clear();
            foreach (var message in messages)
            {
                var lines = System.IO.File.ReadAllLines(message);
                var buffer = new StringBuilder();
                foreach(var line in lines)
                {
                    //if(line.StartsWith("To") || line.StartsWith("From"))
                    //{
                        buffer.Append(line).Append("\n");
                    //}
                }
                buffer.Append("\n--\n");
                Messages.Add(buffer.ToString());
            }

            dataGrid1.ItemsSource = Messages;

            this.dataGrid1.Items.Refresh();

            Console.WriteLine(dataGrid1.Items.Count);
            }
            catch (Exception)
            {

                //throw;
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem mi = e.Source as MenuItem;

            switch (mi.Name)
            {
                case "AddUser":
                    var win = new AddUserWindow();
                    win.ShowDialog();
                    smtpServer.AddAccount(win.UserName);
                    Accounts = smtpServer._accounts;
                    accountsBox.ItemsSource = Accounts;
                    break;
                case "StartService":
                    Start();
                    break;
                case "StopService":
                    Stop();
                    break;
            }
        }

        private void MenuItemName_Click(object sender, RoutedEventArgs e)
        {
            var selected = accountsBox.SelectedItem.ToString();
            accountsBox.SelectedIndex = -1;
            accountsBox.Items.Refresh();
            smtpServer.RemoveAccount(selected);
            Accounts = smtpServer._accounts;
            accountsBox.ItemsSource = Accounts;
        }

        private void OnListViewItemPreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            
        }
    }
}
